import { createRouter, createWebHashHistory } from "vue-router"

//制定路由规则
const routes = [
    {
        path: '/',
        name: '/',
        redirect: '/login'
    },//路由重定向
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login.vue'),
    },

    {
        path: '/home',
        name: 'home',
        component: () => import('@/views/home.vue'),
        redirect: '/home/main',
        children: [
            {
                path: '/home/main',
                name: 'main',
                component: () => import('@/components/main.vue')
            },
            {
                path: '/home/mainin',
                name: 'mainin',
                component: () => import('@/components/mainin.vue')
            },
        ]
    },

]

//创建路由实例
const router = createRouter({
    history: createWebHashHistory(),//设置路由模式
    scrollBehavior: () => ({ left: 0, top: 0 }),//设置滚动行为,默认为滚动到顶部
    routes
})

//全局前置守卫
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token')
    if (to.path === '/login') {
        next()
    } else {
        if (token) {
            next()
        } else {
            next('/login')
        }
    }
})

export default router;